# -*- coding: utf-8 -*-

import os
import sys

from pathlib import Path

from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from qt_material import apply_stylesheet

from main_window import MainWindow
from ui.Ui_main import Ui_MainWindow


# 如果是pyinstaller生成的exe文件执行的，会在sys中添加一个_MEIPASS（即exe释放路径C:\Users\...\AppData\Local\Temp\_MEI***）和一个frozen
# [It also adds the attributes frozen and _MEIPASS to the sys built-in module]，直接从python代码执行则不会
def cwd():
    if getattr(sys, 'frozen', False):
        pathname = Path(r"./")
    else:
        pathname = Path(__file__).parent
    return pathname

def run(cwd):
    app = QApplication(sys.argv)
    dlg = MainWindow(str(cwd))
    
    css = cwd / 'res' / 'custom.css'
    if css.exists():
        apply_stylesheet(app, theme='light_blue.xml', invert_secondary=True)
        stylesheet = app.styleSheet()
        with open(css, encoding="utf-8") as file:
            stylesheet += file.read().format(**os.environ)
        app.setStyleSheet(stylesheet)

    dlg.show()
    dlg.initEditTextCountSlot()
    ret = app.exec()
    return ret
 
def excepthook(excType, excValue, tb):
    QMessageBox.critical(None, '错误', str(excValue))

if __name__ == "__main__":
    sys.excepthook = excepthook
    sys.exit(run(cwd()))
    

# TODO.
# SM2签名验签
# SM2加密、签名随机数
# 复制输出
# 保存密钥
# 封装GMSSL
# About
# 系统托盘（最小化到系统托盘）